package main

import (
	"fmt"
	"net"
	"os"

	"atomgit.com/openlinksaas/extension-proto-gen-go.git/extension_mail_api"
	"atomgit.com/openlinksaas/tencent-mail/config"
	"atomgit.com/openlinksaas/tencent-mail/impl"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"google.golang.org/grpc"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage:%s [config file]\n", os.Args[0])
		return
	}
	servCfg, err := config.ReadConfig(os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}
	apiImpl, err := impl.NewApiImpl(servCfg)
	if err != nil {
		fmt.Println(err)
		return
	}

	grpcServer := grpc.NewServer(grpc.StreamInterceptor(
		grpc_middleware.ChainStreamServer(
			grpc_recovery.StreamServerInterceptor(),
		)),
		grpc.UnaryInterceptor(
			grpc_middleware.ChainUnaryServer(
				grpc_recovery.UnaryServerInterceptor(),
			)),
		grpc.InitialConnWindowSize(1<<30),
		grpc.InitialWindowSize(1<<30),
	)
	extension_mail_api.RegisterExtensionMailApiServer(grpcServer, apiImpl)

	addr, err := net.ResolveTCPAddr("tcp4", servCfg.ListenAddr)
	if err != nil {
		fmt.Println(err)
		return
	}
	li, err := net.ListenTCP("tcp4", addr)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = grpcServer.Serve(li)
	if err != nil {
		fmt.Println(err)
		return
	}
}
